package com.acoffee.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * @author acoffee
 * @create 2021-11-23 17:29
 */
@Controller
public class FileController {

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile, Model model) throws IOException {
        String uploadFile = multipartFile.getOriginalFilename();

        //如果文件名为空，直接回到首页
        if ("".equals(uploadFile)) {
            return "redirect:/index.jsp";
        }

        //上传路径保存设置
        String realPath = request.getServletContext().getRealPath("/images/");
        //上传的文件名
        String filename = multipartFile.getOriginalFilename();

        //如果路径不存在就创建一个
        File realFile = new File(realPath);
        if (!realFile.exists()) {
            realFile.mkdir();
        }

        //将文件复制到我们指定的位置
        multipartFile.transferTo(new File(realPath + File.separator + filename));

        model.addAttribute("msg", "插入成功的路径为：" + new File(realPath + "/" + filename));

        return "success";
    }

    //方式一
    @RequestMapping("/download")
    public String downloads(@RequestParam("filename")String filename,HttpServletResponse response,HttpServletRequest request) throws Exception {
        //下载图片的地址
        String realPath = request.getServletContext().getRealPath("/images/");

        System.out.println(filename);
        //1.设置response响应头
        response.reset();//页面不缓存
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");//二进制传输数据

        //设置响应头
        response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(filename, "UTF-8"));

        File file = new File(realPath, filename);

        //读文件：输入流
        FileInputStream inputStream = new FileInputStream(file);
        //写文件：输出流
        OutputStream outputStream = response.getOutputStream();

        byte[] bytes = new byte[1024];
        int index = 0;
        while ((index=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,index);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();

        return "ok";
    }


    //方式二：
    @RequestMapping("/download1")
    public ResponseEntity<byte[]> downLoad(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws UnsupportedEncodingException {
        String path = request.getServletContext().getRealPath("/images/");

        File file = new File(path + "/" + filename);

        HttpHeaders httpHeaders = new HttpHeaders();

        String downloadFilename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");

        httpHeaders.setContentDispositionFormData("attachment", downloadFilename);

        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return new ResponseEntity(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
        } catch (IOException e) {
            HttpHeaders httpHeader1 = new HttpHeaders();
            httpHeader1.setContentType(MediaType.APPLICATION_JSON);
            return new ResponseEntity("文件名错误!", httpHeader1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
